import 'dart:convert';

import 'package:webview_flutter/webview_flutter.dart';

class FlutterBridge {
  WebViewController webViewController;
  String callbackCode = '';

  FlutterBridge(this.webViewController);

  Result dispatch(String jsonStr, {bool isJson = false}) {
    Map jsonData = jsonDecode(jsonStr);
    String method = jsonData['method'];
    String data = jsonData['data'];
    callbackCode = jsonData['callback'];
    final result = Result();
    result.method = method;
    result.data = data;
    result.callback = (params) => invokeCallbackCode(params, isJson);
    return result;
  }

  invokeCallbackCode(dynamic params, bool isJson) async {
    if (isJson) {
      var json = jsonEncode(params);
      await webViewController.runJavascript("$callbackCode($json)");
      return;
    }
    await webViewController.runJavascript("$callbackCode('$params')");
  }
}

class Result {
  String method = '';
  String data = '';
  late Function callback;
}
